package ua.kharkov.khpi.tarasenko.bach.analysis.utils;

import java.util.List;

import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.Item;
import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.PseudoDbPS;
import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.Sequence;
import ua.kharkov.khpi.tarasenko.bach.analysis.tnr.PseudoDbTNR;
import ua.kharkov.khpi.tarasenko.bach.core.logging.CustomerSession;
import ua.kharkov.khpi.tarasenko.bach.core.logging.TransTypePair;
import ua.kharkov.khpi.tarasenko.bach.core.logging.TransactionType;

public final class AnalysisUtils {

	private AnalysisUtils() {
	}

	public static PseudoDbPS getBoughtItemSets(PseudoDbPS dbToPrune) {
		PseudoDbPS result = new PseudoDbPS();
		for (Sequence seq : dbToPrune.getRows()) {
			Sequence itemSet = new Sequence();
			for (Item item : seq.getItems()) {
				if (item.getTransactionType().equals(TransactionType.BUY)) {
					itemSet.addItem(item);
				}
			}
			if (!itemSet.isEmpty()) {
				itemSet.sortItems();
				result.addRow(itemSet);
			}
		}
		return result;
	}

	public static PseudoDbTNR transformPSToTRNDb(PseudoDbPS psDb) {
		PseudoDbTNR tnrDb = new PseudoDbTNR();

		for (Sequence seq : psDb.getRows()) {
			tnrDb.addTransaction(seq.getItemsIds());
		}

		return tnrDb;
	}

	public static PseudoDbPS transformToPseudoPsBd(List<CustomerSession> list) {
		PseudoDbPS db = new PseudoDbPS();

		for (CustomerSession session : list) {
			Sequence seq = new Sequence();
			for (TransTypePair pair : session.getTransactions()) {
				Item item = Item.getItem(pair.getItemId().toString());
				item.setTransactionType(pair.getTransactionType());
				seq.addItem(item);
			}
			db.addRow(seq);
		}
		return db;
	}
	
	/**
	 * Removes bought and cart transactions from access sequences
	 * 
	 * @param psDb
	 */
	public static PseudoDbPS getAccessDB(PseudoDbPS psDb) {
		PseudoDbPS result = new PseudoDbPS();
		for (Sequence seq : psDb.getRows()) {
			Sequence itemSet = new Sequence();
			for (Item item : seq.getItems()) {
				if (!(item.getTransactionType().equals(TransactionType.BUY) || item.getTransactionType().equals(TransactionType.CART))) {
					itemSet.addItem(item);
				}
			}
			if (!itemSet.isEmpty()) {
				itemSet.sortItems();
				result.addRow(itemSet);
			}
		}
		return result;
	}
}
